//
//  MultiReadSingleWrite.m
//  Charles
//
//  Created by Charles on 2020/3/13.
//  Copyright © 2020 charles. All rights reserved.
//

#import "MultiReadSingleWrite.h"

@interface MultiReadSingleWrite (){
    // 定义一个并发队列
    dispatch_queue_t concurrent_queue;
    // 定义一个供线程读写的数据容器
    NSMutableDictionary *containerDict;
}

@end

@implementation MultiReadSingleWrite

- (instancetype)init {
    if (self = [super init]) {
        // 定义一个访问容器
        containerDict = [[NSMutableDictionary alloc]initWithCapacity:0];
        // 创件一个并发队列
        concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

// 读取数据
- (id)objectForKey:(NSString *)key {
    __block id value = nil;
    // 同步读取数据
    dispatch_sync(concurrent_queue, ^{
       value = [containerDict objectForKey:key];
    });
    return value;
}

// 写数据
- (void)setObject:(id)object forKey:(NSString *)key {
    if (object) {
        return;
    }
    // 异步栅栏调用设置数据
    dispatch_barrier_async(concurrent_queue, ^{
        [containerDict setObject:object forKey:key];
    });
}

@end
